package cn.sdxx.qddata.security;


import cn.sdxx.qddata.utils.JwtTokenUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * 重写DefaultWebSessionManager
 * @Description 重写Jwt会话管理
 * 添加jwtToken的jti作为会话的唯一标识
 */
@Component
public class ShiroSessionManager extends DefaultWebSessionManager {
	
	private static final String AUTHORIZATION = "Authorization";

    // 自定义：无状态的请求 类型
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    public ShiroSessionManager(){
        super();
    }

    @Autowired
    JwtTokenUtils jwtUtils;

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response){
        String jwtToken = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        if(!StringUtils.hasLength(jwtToken)){
            //如果没有携带id参数则按照父类的方式在cookie进行获取
            return super.getSessionId(request, response);
        }else{
            //如果请求头中有 authToken 则其值为jwtToken，然后解析出会话session
            Claims claims = jwtUtils.parseToken(jwtToken);
            String shiroSessionId = (String) claims.get("jti");  //claims.getId()
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,shiroSessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);
            return shiroSessionId;
        }
    }

}
